<?php
namespace app\kefu\merchant;

use app\common\controller\Common;
use app\kefu\model\KfShop as KfShopModel;

class Login extends Common
{
    
    public function index()
    {
        if(session('?merchant')){
            $this->redirect(url('index/index'));
        }
        //session('service_login_error',0);
        $loginError = (int)session('service_login_error');
        $this->assign([
            'loginError'=>$loginError
            ,'userinfo'=>session('merchant')
        ]);

        return $this->fetch('merchant/login');
    }

    public function doLogin()
    {
        if(request()->isAjax()){
            
            $userName = input('post.username');
            $password = input('post.password');
            $captcha  = input('post.captcha');
            $loginError = (int)session('service_login_error');
            if ($loginError >= 3) {
                if (empty($captcha)) {
                    return $this->error('请输入验证码');
                }
                if (!captcha_check($captcha)) {
                    return $this->error('验证码错误');
                }
            }
            try {
                $res = KfShopModel::login($userName,$password);
                session('service_login_error',0);
            } catch (\Exception $e) {
                session('service_login_error',$loginError+1);
                return $this->error('['.$e->getCode().']'.$e->getMessage(),null,['service_login_error_num'=>$loginError+1]);
            }
            
            $this->success('登录成功',url('index/index'));
        }

        $this->error('非法访问');
    }

    public function logOut()
    {
        session('merchant', null);
        session('login_merchant_sign', null);

        $this->redirect(url('login/index'));
    }
}